package com.youxin.foundation.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 日期工具类
 * 
 * @author yingde.cao
 *
 */
public class DateUtil {
	public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String YYYYMMDDHHMM = "yyyyMMddHHmm";

	/**
	 * 取小时间
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static Date min(Date date1, Date date2) {
		if (date1 == null) {
			return date2;
		}
		if (date2 == null) {
			return date1;
		}
		if (date1.compareTo(date2) < 0) {
			return date1;
		}
		return date2;
	}

	/**
	 * 取大的时间
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static Date max(Date date1, Date date2) {
		if (date1 == null) {
			return date2;
		}
		if (date2 == null) {
			return date1;
		}
		if (date1.compareTo(date2) > 0) {
			return date1;
		}
		return date2;
	}

	/**
	 * 时间差 后面的时间减去前面的时间差
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getTimeDiff(Date date1, Date date2) {
		return date2.getTime() - date1.getTime();
	}

	/**
	 * 时间差是否大于给定的时间
	 * 
	 * @param date1
	 * @param date2
	 * @param millisecond
	 * @return
	 */
	public static boolean isTimeDiffGreaterOrEqual(Date date1, Date date2, long millisecond) {
		long diff = getTimeDiff(date1, date2);
		return diff >= millisecond;
	}

	/**
	 * 是否在之间
	 * 
	 * @param date1
	 * @param date2
	 * @param compareDate
	 * @return
	 */
	public static boolean between(Date date1, Date date2, Date compareDate) {
		return compareDate.compareTo(date1) >= 0 && compareDate.before(date2);
	}

	public static Calendar dateToCalendar(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}

	public static Date addDayDate(Date date, int days) {
		return addDateWithField(date, days, Calendar.DATE);
	}

	public static Date addDateWithField(Date date, int offset, int field) {
		Calendar calendar = dateToCalendar(date);
		calendar.add(field, offset);
		return calendar.getTime();
	}

	public static String formatTime(long ms) {
		int ss = 1000;
		int mi = ss * 60;
		int hh = mi * 60;
		int dd = hh * 24;

		long day = ms / dd;
		long hour = (ms - day * dd) / hh;
		long minute = (ms - day * dd - hour * hh) / mi;
		long second = (ms - day * dd - hour * hh - minute * mi) / ss;
		long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

		StringBuffer sb = new StringBuffer();
		if (day > 0) {
			sb.append(day + "天");
		}
		if (hour > 0) {
			sb.append(hour + "小时");
		}
		if (minute > 0) {
			sb.append(minute + "分");
		}
		if (second > 0) {
			sb.append(second + "秒");
		}
		if (milliSecond > 0) {
			sb.append(milliSecond + "毫秒");
		}
		return sb.toString();
	}

	/**
	 * Calendar计算,增加或减少年月日等
	 * 
	 * @param calendar
	 *            日历表
	 * @param field
	 *            字段
	 * @param diff
	 *            差距
	 * @return 日历
	 */
	public static Calendar calendar(Calendar calendar, int field, int diff) {
		calendar.add(field, diff);
		return calendar;
	}

	public static Calendar calendarMinute(Calendar calendar, int diff) {
		calendar.add(Calendar.MINUTE, diff);
		return calendar;
	}
	
	/**
	 * 是否闰年
	 * @param date 时间
	 * @return boolean
	 */
	public static boolean isLeapYear(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int a = calendar.get(Calendar.YEAR);
		if ((a % 4 == 0 && a % 100 != 0) || a % 400 == 0) {
			return true;
		} else {
			return false;
		}
	}

	public static String calendarFormat(Calendar calendar, String format) {
		Date date = calendar.getTime();
		return dateToString(date, format);
	}

	/**
	 * 获取年月日字符串
	 * 
	 * @param calendar
	 * @return YYYYMMDDHHMM
	 */
	public static String getFormatTime(Calendar calendar) {
		return calendarFormat(calendar, YYYYMMDDHHMM);
	}

	/**
	 * 获取格式化字符串 YYYYMMDDHHMM
	 * 
	 * @return String
	 */
	public static String getFormatTime() {
		return getFormatTime(Calendar.getInstance());
	}

	/**
	 * 获取格式化字符串
	 * 
	 * @param minuteDiff
	 *            分差
	 * @return
	 */
	public static String getFormatTime(int minuteDiff) {
		Calendar calendar = Calendar.getInstance();
		return getFormatTime(minuteDiff, calendar);
	}

	public static String getFormatTime(int minuteDiff, Calendar calendar) {
		calendarMinute(calendar, minuteDiff);
		return getFormatTime(calendar);
	}

	/**
	 * 获取格式化数字 YYYYMMDDHHMM
	 * 
	 * @return Long
	 */
	public static Long getFormatTimeLong() {
		return Long.parseLong(getFormatTime(Calendar.getInstance()));
	}

	public static Date stringToDate(String dateString) {
		return stringToDate(dateString, DEFAULT_FORMAT);
	}

	public static Date stringToDate(String dateString, String format) {
		try {
			DateFormat dateFormat = new SimpleDateFormat(format);
			return dateFormat.parse(dateString);
		} catch (ParseException e) {
			return null;
		}
	}

	public static String dateToString(Date date, String format) {
		try {
			DateFormat dateFormat = new SimpleDateFormat(format);
			return dateFormat.format(date);
		} catch (Exception e) {
			return "";
		}
	}

	public static String dateToString(Date date) {
		return dateToString(date, DEFAULT_FORMAT);
	}

	/**
	 * 转换10位时间戳工具，返回String的“yyyy-MM-dd”时间
	 * 
	 * @param datetime
	 *            int型10位时间戳
	 */
	public static String formatDate(int datetime) {
		SimpleDateFormat sdf = null;
		String dateTime = null;
		try {
			sdf = new SimpleDateFormat(DEFAULT_FORMAT);
			String strDatatime = datetime + "000";
			Long lDatatime = Long.parseLong(strDatatime);
			dateTime = sdf.format(lDatatime);
		} catch (Exception e) {
			// TODO 处理异常
			e.printStackTrace();
		}
		return dateTime;
	}

	/**
	 * @Title: getDateForInt @Description: 日期转int，统一php格式 @param @return @return
	 * int @throws
	 */
	public static int getDateForInt() {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		long time = 0;
		try {
			time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return (int) (time / 1000);
	}
	/**
	 * @Title: getDateForInt @Description: 日期转int，统一php格式 @param @return @return
	 * int @throws
	 */
	public static int getDateForInt(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long time = 0;
		try {
			time = sdf.parse(date).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return (int) (time / 1000);
	}

	/**
	 * @Description: int转日期时间(统一php格式)
	 * @author Kris.wang
	 * @param minuteTime
	 * @param format
	 * @return
	 */
	public static String minuteTimeToString(String minuteTime, String format) {
		try {
			Long lMinuteTime = new Long(minuteTime);
			Date date = new Date(lMinuteTime * 1000);
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * @Description: Long类型转日期时间
	 * @author Kris.wang
	 * @param msecond
	 * @param format
	 * @return
	 */
	public static String msecondTimeToString(Long msecond, String format) {
		try {
			Long lMinuteTime = new Long(msecond);
			Date date = new Date(lMinuteTime);
			return new SimpleDateFormat("yyyy-MM-dd").format(date);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * @Description: 字符串时间格式转Long
	 * @author Kris.wang
	 * @param formatTime
	 * @return
	 */
	public static Long formatTimeToLong(String formatTime) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.parse(formatTime).getTime();
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String formatSecondToTime(long seconds)
	{
		long hours=seconds/3600;
		long mod=seconds%3600;
		long minutes=mod/60;
		mod=mod%60;
		long second=mod;
		StringBuilder sBuilder=new StringBuilder();
		if(hours>0)
		{
			sBuilder.append(hours+"小时");
		}
		if(minutes>0)
		{
			sBuilder.append(minutes+"分");
		}
		if(second>0||sBuilder.length()==0)
		{
			sBuilder.append(second+"秒");
		}
		return sBuilder.toString();
	}

	 /**
	  * @Title: getDayBegin 
	  * @Description: 获取当天的开始时间
	  * @param @return
	  * @return java.util.Date
	  * @throws
	  */
    public static java.util.Date getDayBegin() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }
    
    /**
     * @Title: getDayEnd 
     * @Description: 获取当天的结束时间
     * @param @return
     * @return java.util.Date
     * @throws
     */
    public static java.util.Date getDayEnd() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }
    
    /**
     * @Title: getBeginDayOfWeek 
     * @Description: 获取本周的开始时间
     * @param @return
     * @return Date
     * @throws
     */
    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }
    
    /**
     * @Title: getEndDayOfWeek 
     * @Description: 获取本周的结束时间
     * @param @return
     * @return Date
     * @throws
     */
    public static Date getEndDayOfWeek(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(getBeginDayOfWeek());  
        cal.add(Calendar.DAY_OF_WEEK, 6); 
        Date weekEndSta = cal.getTime();
        return getDayEndTime(weekEndSta);
    }
    
   /**
    * @Title: getDayStartTime 
    * @Description: 获取某个日期的开始时间
    * @param @param d
    * @param @return
    * @return Timestamp
    * @throws
    */
    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if(null != d) calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        //calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }
    
    /**
     * @Title: getDayEndTime 
     * @Description: 获取某个日期的结束时间
     * @param @param d
     * @param @return
     * @return Timestamp
     * @throws
     */
    public static Timestamp getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if(null != d) calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }
    
    /**
     * @Title: getDayStartTimeString 
     * @Description: 获取某个日期的开始时间
     * @param @param d
     * @param @return
     * @return String
     * @throws
     */
    public static String getDayStartTimeString(Date d) {
        Calendar calendar = Calendar.getInstance();
        if(null != d) calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTimeInMillis());

    }
    /**
     * @Title: getDayEndTimeString 
     * @Description: 获取某个日期的结束时间
     * @param @param d
     * @param @return
     * @return String
     * @throws
     */
    public static String getDayEndTimeString(Date d) {
    	Calendar calendar = Calendar.getInstance();
    	if(null != d) calendar.setTime(d);
    	calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTimeInMillis());
    }
    
    /**
     * @Title: getBeginDayOfMonth 
     * @Description: 获取本月的开始时间
     * @param @return
     * @return Date
     * @throws
     */
    public static Date getBeginDayOfMonth() {
       Calendar calendar = Calendar.getInstance();
       calendar.set(getNowYear(), getNowMonth() - 1, 1);
       return getDayStartTime(calendar.getTime());
   }
    /**
     * @Title: getEndDayOfMonth 
     * @Description: 获取本月的结束时间
     * @param @return
     * @return Date
     * @throws
     */
    public static Date getEndDayOfMonth() {
       Calendar calendar = Calendar.getInstance();
       calendar.set(getNowYear(), getNowMonth() - 1, 1);
       int day = calendar.getActualMaximum(5);
       calendar.set(getNowYear(), getNowMonth() - 1, day);
       return getDayEndTime(calendar.getTime());
   }
	/**
	 * @Title: getNowYear 
	 * @Description: 获取今年是哪一年
	 * @param @return
	 * @return Integer
	 * @throws
	 */
	public static Integer getNowYear() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return Integer.valueOf(gc.get(1));
	}

	/**
	 * @Title: getNowMonth 
	 * @Description: 获取本月是哪一月
	 * @param @return
	 * @return int
	 * @throws
	 */
	public static int getNowMonth() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return gc.get(2) + 1;
	}
	public static String getFormatString(Date date){
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}
	/**
	 * 日期相减得到月
	 * @Title: main 
	 * @Description: TODO
	 * @param @param args
	 * @return void
	 * @throws
	 */
	public static int getRemainingMonths(String d1,String d2){
		int result = 0;
		try {
	        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");
	        Calendar c = Calendar.getInstance();
	        c.setTime(sdf.parse(d1));
	        int year1 = c.get(Calendar.YEAR);
	        int month1 = c.get(Calendar.MONTH);
	         
				c.setTime(sdf.parse(d2));
	        int year2 = c.get(Calendar.YEAR);
	        int month2 = c.get(Calendar.MONTH);
	         
	        if(year1 == year2) {
	            result = month1 - month2;
	        } else {
	            result = 12*(year1 - year2) + month1 - month2;
	        }
			} catch (ParseException e) {
				e.printStackTrace();
			}
		return result;
    }
	
	/**
	 * @Title: yearDateDiff 
	 * @Description: 计算两个日期相差年数  
	 * @param @param startDate
	 * @param @param endDate
	 * @param @return
	 * @return int
	 * @throws
	 */
	public static int yearDateDiff(String startDate,String endDate){  
	   Calendar calBegin = Calendar.getInstance(); //获取日历实例  
	   Calendar calEnd = Calendar.getInstance();  
	   calBegin.setTime(stringToDate(startDate,"yyyy")); //字符串按照指定格式转化为日期  
	   calEnd.setTime(stringToDate(endDate,"yyyy"));  
	   return calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR);  
	}  
	
}
